package com.rds.document.controller;

import com.github.pagehelper.PageHelper;
import com.rds.common.annotation.Log;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.core.domain.entity.Folder;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.service.DocumentService;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.StringUtils;
import com.rds.common.utils.poi.ExcelUtil;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.common.utils.rds.HistoryRecordUtil;
import com.rds.document.service.IFolderService;
import com.rds.document.service.IRdaFolderRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 文件夹Controller
 *
 * @author rds
 * @date 2021-07-05
 */
@RestController
@RequestMapping("/pms/folder")
public class RdaFolderController extends BaseController
{
    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private DocumentService documentService;
    /** 文件夹表名 */
    private static final String tableName = "rda_folder";
    @Autowired
    private IFolderService folderService;

    /**
     * 查询文件夹列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        List<HashMap<String,Object>> list=dynamicService.selectDataList(tableName,queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询文件夹列表
     */
    @GetMapping("/childList")
    public TableDataInfo childList(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        if(parameterMap.get("parentid")!=null && !parameterMap.get("parentid").equals("")){
            queryWrapper.add("and parentid="+parameterMap.get("parentid"));
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        List<HashMap<String,Object>> list=dynamicService.selectDataList(tableName,queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询文件夹下的文档列表
     */
    @GetMapping("/doclist")
    public TableDataInfo doclist(HttpServletRequest request)
    {
        startPage();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        /*根据文件夹id查文件夹下的文档**/
        List<HashMap<String,Object>> list=documentService.selectFolderDoc(Long.valueOf(parameterMap.get("parentid")));
        return getDataTable(list);
    }

    /**
     * 获取文件夹详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:folder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        HashMap<String,Object> folder=dynamicService.selectDataById(tableName,id);
        return AjaxResult.success(folder);
    }

    /**
     * 新增文件夹
     */
    @PreAuthorize("@ss.hasPermi('pms:folder:add')")
    @Log(title = "文件夹", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> data)
    {
        if(SecurityUtils.verifyPermissions("created", String.valueOf(data.get("stateid")))){
            return error("您没有此状态的创建权限！");
        }
        Long userId = SecurityUtils.getUserId();
        Long fid=SnowFlakeUtils.nextId();
        Map<String, Object> map=new HashMap<>();
        map.put("id",fid);
        map.put("name",String.valueOf(data.get("name")));
        map.put("description",String.valueOf(data.get("description")));
        map.put("parentid",String.valueOf(data.get("parentid")));
        map.put("objectid",String.valueOf(data.get("projectid")));
        map.put("typeid",String.valueOf(data.get("typeid")));
        map.put("policyid",String.valueOf(data.get("policyid")));
        map.put("stateid",String.valueOf(data.get("stateid")));
        map.put("ownerid",userId);
        map.put("revision",String.valueOf(data.get("revision")));
        map.put("create_time", DateUtils.getNowDate());
        int num=dynamicService.insertData("rda_folder",map);
        if(num > 0){
            new HistoryRecordUtil(dynamicService).recordHistory(Long.valueOf(String.valueOf(data.get("projectid"))),"新增文件夹", Math.toIntExact(Long.parseLong(String.valueOf(data.get("stateid")))),"文档库管理","文件夹名称："+data.get("name"));
        }
        return toAjax(num);
    }

    /**
     * 修改文件夹
     */
    @PreAuthorize("@ss.hasPermi('pms:folder:edit')")
    @Log(title = "文件夹", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> data)
    {
        if(SecurityUtils.verifyPermissions("modify", String.valueOf(data.get("stateid")))){
            return error("您没有此状态的修改权限！");
        }
        Map<String, Object> map=new HashMap<>();
        map.put("name",String.valueOf(data.get("name")));
        map.put("description",String.valueOf(data.get("description")));
        map.put("modify_time", DateUtils.getNowDate());
        ArrayList<String> updateWrapper=new ArrayList<>();
        updateWrapper.add("id="+data.get("id"));
        int num=dynamicService.updateData("rda_folder",map,updateWrapper);
        if(num>0){
            new HistoryRecordUtil(dynamicService).recordHistory(Long.valueOf(String.valueOf(data.get("objectid"))),"修改文件夹", Math.toIntExact(Long.parseLong(String.valueOf(data.get("stateid")))),"文档库管理","文件夹名称："+data.get("name"));
        }
        return toAjax(num);
    }

    /**
     * 删除文件夹
     */
    @Log(title = "文件夹", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int successNum=0;
        int verifyNum=0;
        List<HashMap<String,Object>> folderList= dynamicService.selectListByIds(tableName,ids);
        for (HashMap<String,Object> folder:folderList){
            if(SecurityUtils.verifyPermissions("remove", String.valueOf(folder.get("stateid")))){
                verifyNum++;
            }else{
                Long folderId=(Long) folder.get("id");
                int num=dynamicService.deleteDataById(tableName, folderId);
                if(num>0){
                    //删除文件夹关系
                    ArrayList<String> folderWrapper=new ArrayList<>();
                    folderWrapper.add("folderid="+folderId);
                    dynamicService.deleteData("rda_folder_rel", folderWrapper);
                    new HistoryRecordUtil(dynamicService).recordHistory(Long.valueOf(String.valueOf(folder.get("objectid"))),"删除文件夹", (int) folder.get("stateid"),"文档库管理", "文件夹名称："+folder.get("name"));
                    successNum++;
                }
            }
        }
        return AjaxResult.getRemoveAjaxResult(successNum, verifyNum);
    }

    /**
     * 加载列表树
     */
    @GetMapping("/getFolder")
    public AjaxResult getFolderList(HttpServletRequest request)
    {
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        if(parameterMap.get("parentid")!=null && !parameterMap.get("parentid").equals("")){
            queryWrapper.add("and parentid="+parameterMap.get("parentid"));
        }
        List<HashMap<String,Object>> list=dynamicService.selectDataList(tableName,queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 移除
     * 移除文档和文件夹的关联
     */
    @Log(title = "移除文件夹文档", businessType = BusinessType.DELETE)
    @DeleteMapping("/batchRemove/{ids}")
    public AjaxResult batchRemove(@PathVariable Long[] ids)
    {
        return toAjax(dynamicService.deleteDataByIds("rda_folder_rel",ids));
    }
}
